package com.bicon.life.core.base.repository.jpa;

import com.bicon.life.core.base.common.Enum.DateStyle;
import com.bicon.life.core.base.common.utils.StringUtils;
import com.bicon.life.core.base.common.utils.DateUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class SearchFilter {
	//LIKEIGNORE 模糊查找不区分大小写
	//LIKE 模糊查找区分大小写
	public enum Operator{
		EQ, IN, ISNULL, LIKE, GT, LT, GTE, LTE, NE,LIKEIGNORE
	}

	public String fieldName;
	public Object value;
	public Operator operator;

	public SearchFilter(String fieldName, Operator operator, Object value) {
		this.fieldName = fieldName;
		this.value = value;
		this.operator = operator;
	}

	public static List<SearchFilter> parse(Map<String, Object> filterParams) {
		List<SearchFilter> filters = new ArrayList<>();
		for (Entry<String, Object> entry : filterParams.entrySet()) {
			String[] names = entry.getKey().split("_");
			Object value = entry.getValue();
			if (names.length < 2) {
				throw new IllegalArgumentException(entry.getKey() + " is not a valid search filter name");
			}
			if(names.length == 3){
				if("SHORTDATE".equals(names[2])){
					String fieldValue = (String)value;
					if(!StringUtils.isEmpty(fieldValue)){
						value = fieldValue.replace("T", "").replace(":", "").replace("-", "").subSequence(0, 8);
					}
				}
				if("DATE".equals(names[2])){
					String fieldValue = (String)value;
					if(!StringUtils.isEmpty(fieldValue)){
						if("LTE".equals(names[0])){
						 	try {
								Date d= DateUtil.StringToDate(value.toString(), DateStyle.YYYY_MM_DD_HH_MM_SS);
								value=DateUtil.DateToString(d,DateStyle.YYYY_MM_DD_HH_MM_SS_EN);
						 	} catch (Exception e) {
								e.printStackTrace();
							} 
						}else if("GTE".equals(names[0])){
							try {
								Date d= DateUtil.StringToDate(value.toString(), DateStyle.YYYY_MM_DD_HH_MM_SS);
								value=DateUtil.DateToString(d,DateStyle.YYYY_MM_DD_HH_MM_SS_EN);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}else{
							value = fieldValue+ "000000";
						}
					}
				}
			}
			SearchFilter filter = new SearchFilter(names[1], Operator.valueOf(names[0]), value);
			if(!StringUtils.isEmpty(entry.getValue())){
				filters.add(filter);
			}
		}
		return filters;
	}
}
